//
//  MNDWechatRegistViewController.m
//  minidai
//
//  Created by Vitas on 2018/7/20.
//  Copyright © 2018年 迷你贷. All rights reserved.
//

#import "MNDWechatRegistViewController.h"
#import <UMPush/UMessage.h>
#import "RSAUtil.h"

@interface MNDWechatRegistViewController ()

@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;
@property (weak, nonatomic) IBOutlet UILabel *passwordTipLabel;
@property (weak, nonatomic) IBOutlet UIView *passwordBottomLineView;


@property (copy, nonatomic) NSString *password;


@end

@implementation MNDWechatRegistViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
    
}

- (void)setupUI {
    
    kdeclare_weakself;
    RAC(self, password) = [RACSignal combineLatest:@[RACObserve(self, passwordTextField.text)] reduce:^id (NSString *pwd){
        return pwd;
    }];
   
    __block UITextField *pwdTextField = self.passwordTextField;
    [self.passwordTextField.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
        if (x.length > 16) {
            pwdTextField.text = [x substringToIndex:16];
        }
    }];
    
    
    [self.passwordTextField bk_addEventHandler:^(id sender) {
        if (weakSelf.passwordTextField.text.length > 0) {
            weakSelf.passwordTipLabel.hidden = NO;
            weakSelf.passwordTipLabel.textColor = [UIColor colorWithRed:255/255.0 green:110/255.0 blue:63/255.0 alpha:1.0];
            weakSelf.passwordBottomLineView.backgroundColor = [UIColor colorWithRed:255/255.0 green:110/255.0 blue:63/255.0 alpha:1.0];
        }else {
            weakSelf.passwordTipLabel.hidden = YES;
        }
        
    } forControlEvents:UIControlEventEditingChanged];
    
    [self.passwordTextField bk_addEventHandler:^(id sender) {
        if(weakSelf.passwordTextField.text.length <= 0) {
            weakSelf.passwordTipLabel.hidden = YES;
        }
        weakSelf.passwordTipLabel.textColor = [UIColor colorWithRed:203/255.0 green:203/255.0 blue:203/255.0 alpha:1.0];
        weakSelf.passwordBottomLineView.backgroundColor = [UIColor colorWithRed:239/255.0 green:239/255.0 blue:244/255.0 alpha:1.0];
    } forControlEvents:UIControlEventEditingDidEnd];
    
    
}

- (IBAction)wexinRegistAction:(UIButton *)sender {
    
    kdeclare_weakself;
    if (self.password.length <= 0) {
        [NetworkProgressHUD showHudMsg:@"请输入密码"];
        return;
    }
    [NetworkProgressHUD showHud];
    NSDictionary *dict = @{
                           @"user_phone":self.userPhone,
                           @"user_login_password":self.password,
                           @"unionid":self.user.credential.rawData[@"unionid"],
                           @"open_name":self.user.nickname,
                           @"open_img": self.user.icon,
                           @"open_sex": self.user.gender == 0 ? @(-1):@(1),
                           @"open_type": @"1"
                           };
    [APIManager sendRequestWithURL:API_WECHAT_REGIST parameters:[MNDSign signedParamWithDict:dict] method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        [NetworkProgressHUD hideHud];
        if (responseModel.status == ResponseSuccess) {
            
//            [NetworkProgressHUD showHudMsg:responseModel.msg[@"success"]];
            MNDLoginUserModel *userModel = [MNDLoginUserModel mj_objectWithKeyValues:responseModel.data];
            //更新数据库
            [MNDLoginUserModel addOrUpdateUser:userModel];
            
            //设置用户标识
            [Bugly setUserIdentifier:userModel.user_id];
            
            [weakSelf setHTTPHeaders];
            
            //设置消息推送别名
            [UMessage setAlias:userModel.user_code type:@"minidai" response:^(id  _Nonnull responseObj, NSError * _Nonnull error) {
                if (error) {
                    NSLog(@"设置别名失败: %@", error);
                } else {
                    NSLog(@"设置别名成功: %@", responseObj);
                }
            }];
            
            [weakSelf dismissViewControllerAnimated:YES completion:nil];
        }else {
            [NetworkProgressHUD showHudMsg:responseModel.data[@"error"]];
        }
        
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (IBAction)showOrHidePasswordAction:(UIButton *)sender {
    sender.selected = !sender.isSelected;
    
    self.passwordTextField.secureTextEntry = !sender.isSelected;

}

- (void)setHTTPHeaders {
    //传userCode
    MNDLoginUserModel *user = [MNDLoginUserModel currentLoginUser];
    if (user.user_code.length > 0) {
        NSString *encryText = [RSAUtil encryptString:[NSString stringWithFormat:@"%@", user.user_code] publicKey:RSA_PUBLIC_KEY];
        NSString *unreserved = @"";
        NSMutableCharacterSet *allowed = [NSMutableCharacterSet alphanumericCharacterSet];
        [allowed addCharactersInString:unreserved];
        
        NSString *encodeEncryText = [encryText stringByAddingPercentEncodingWithAllowedCharacters:allowed];
        [APIManager setGeneralHeaderValue:encodeEncryText forField:@"USERCODE"];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



/*
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:<#@"reuseIdentifier"#> forIndexPath:indexPath];
    
    // Configure the cell...
    
    return cell;
}
*/

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
